import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";

const ext = {
	name: "CodeBuddy.SwitchAny.RefreshButton",
	async beforeRegisterNodeDef(nodeType, nodeData, app) {
		if (nodeData.name === "SwitchAny") {
			const onNodeCreated = nodeType.prototype.onNodeCreated;
			nodeType.prototype.onNodeCreated = function () {
				onNodeCreated?.apply(this, arguments);

				// Add a button widget to the node
				const button = this.addWidget("button", "Save & Refresh UI", "save_refresh", async () => {
                    // 1. Collect all labels from the node's widgets
                    const labels = [];
                    for (const widget of this.widgets) {
                        if (widget.name && widget.name.startsWith("label_")) {
                            if (widget.value && widget.value.trim() !== "") {
                                labels.push(widget.value.trim());
                            }
                        }
                    }

                    try {
                        // 2. POST the collected labels to our custom Python endpoint
                        const response = await api.fetchApi("/switch_any/save_labels", {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            body: JSON.stringify({ labels: labels }),
                        });

                        if (response.status !== 200) {
                            const errorData = await response.json();
                            alert(`Error saving labels: ${errorData.message}`);
                            return;
                        }
                        
                        // 3. On successful save, reload the page to update the UI
                        window.location.reload();

                    } catch (error) {
                        console.error("Failed to save labels:", error);
                        alert(`Failed to save labels: ${error}`);
                    }
				});

                // FIX: Mark the button as not serializable to prevent its value from being saved in the workflow.
                button.serializable = false;
			};
		}
	},
};

app.registerExtension(ext);